<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>翻译记录管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="layui/css/layui.css" media="all">
    <style>
        .layui-table-tool-temp {
            padding-right: 10px !important;
        }
        .layui-table-tool-self {
            padding-right: 0 !important;
        }
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">翻译记录管理</div>
                <div class="layui-card-body">
                    <table class="layui-hide" id="transTable" lay-filter="transTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="batchDelete">批量删除</button>
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="toTransPage">在线翻译</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="langTpl">
    {{#  if(d.lang === 'en'){ }}
    英语
    {{#  } else if(d.lang === 'jp'){ }}
    日语
    {{#  } else if(d.lang === 'fra'){ }}
    法语
    {{#  } else { }}
    {{ d.lang }}
    {{#  } }}
</script>

<script src="layui/layui.js" charset="utf-8"></script>
<script>
    layui.use(['table', 'layer', 'form'], function(){
        var table = layui.table
            ,layer = layui.layer
            ,form = layui.form;

        // 渲染表格
        table.render({
            elem: '#transTable'
            ,url:'/transRec' // 数据接口
            ,method: 'GET'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print']
            ,parseData: function(res){ //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg":"", //解析提示文本
                    "count": res.totalElements, //解析数据长度
                    "data": res.content //解析数据列表
                };
            }
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'ID', width:80, sort: true, fixed: 'left'}
                ,{field:'fromText', title:'原文', width:200}
                ,{field:'lang', title:'目标语言', width:120, templet: '#langTpl'}
                ,{field:'toText', title:'译文', width:200}
                ,{field:'transDate', title:'翻译时间', width:200, sort: true}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
            ]]
            ,page: true
            ,limit: 10
            ,limits: [10, 20, 30, 50]
            ,request: {
                pageName: 'page' //页码的参数名称，默认：page
                ,limitName: 'size' //每页数据量的参数名，默认：limit
            }
            ,response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,statusCode: 0 //规定成功的状态码，默认：0
                ,msgName: 'msg' //规定状态信息的字段名称，默认：msg
                ,countName: 'count' //规定数据总数的字段名称，默认：count
                ,dataName: 'data' //规定数据列表的字段名称，默认：data
            }
        });

        //头工具栏事件
        table.on('toolbar(transTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    openAddDialog();
                    break;
                case 'toTransPage':
                    window.location.href = 'index.html';
                    break;
                case 'batchDelete':
                    var data = checkStatus.data;
                    if(data.length === 0) {
                        layer.msg('请选择要删除的数据');
                        return;
                    }
                    var ids = [];
                    data.forEach(function(item) {
                        ids.push(item.id);
                    });
                    batchDelete(ids);
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(transTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('确定删除这条记录吗？', function(index){
                    deleteRecord(data.id, function() {
                        obj.del();
                        layer.close(index);
                    });
                });
            } else if(obj.event === 'edit'){
                openEditDialog(data);
            }
        });

        // 打开添加对话框
        function openAddDialog() {
            layer.open({
                type: 1
                ,title: '添加翻译记录'
                ,area: ['500px', '400px']
                ,shade: 0.6
                ,maxmin: false
                ,anim: 1
                ,content: `
                    <div style="padding: 20px;">
                        <form class="layui-form" action="" lay-filter="addForm">
                            <div class="layui-form-item">
                                <label class="layui-form-label">原文</label>
                                <div class="layui-input-block">
                                    <textarea name="fromText" placeholder="请输入原文" class="layui-textarea"></textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">目标语言</label>
                                <div class="layui-input-block">
                                    <select name="lang">
                                        <option value="en">英语</option>
                                        <option value="jp">日语</option>
                                        <option value="fra">法语</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">译文</label>
                                <div class="layui-input-block">
                                    <textarea name="toText" placeholder="请输入译文" class="layui-textarea"></textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="addSubmit">立即提交</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                    </div>
                `
                ,success: function(layero, index){
                    layui.use('form', function(){
                        var form = layui.form;
                        form.render();

                        //监听提交
                        form.on('submit(addSubmit)', function(data){
                            addRecord(data.field, function() {
                                layer.close(index);
                                table.reload('transTable');
                            });
                            return false;
                        });
                    });
                }
            });
        }

        // 打开编辑对话框
        function openEditDialog(record) {
            layer.open({
                type: 1
                ,title: '编辑翻译记录'
                ,area: ['500px', '400px']
                ,shade: 0.6
                ,maxmin: false
                ,anim: 1
                ,content: `
                    <div style="padding: 20px;">
                        <form class="layui-form" action="" lay-filter="editForm">
                            <input type="hidden" name="id" value="` + record.id + `">
                            <div class="layui-form-item">
                                <label class="layui-form-label">原文</label>
                                <div class="layui-input-block">
                                    <textarea name="fromText" readonly placeholder="请输入原文" class="layui-textarea">` + (record.fromText || '') + `</textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">目标语言</label>
                                <div class="layui-input-block">
                                    <select name="lang"   disabled >
                                        <option value="en" ` + (record.lang === 'en' ? 'selected' : '') + `>英语</option>
                                        <option value="jp" ` + (record.lang === 'jp' ? 'selected' : '') + `>日语</option>
                                        <option value="fra" ` + (record.lang === 'fra' ? 'selected' : '') + `>法语</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">译文</label>
                                <div class="layui-input-block">
                                    <textarea name="toText" placeholder="请输入译文" class="layui-textarea">` + (record.toText || '') + `</textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="editSubmit">立即提交</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                    </div>
                `
                ,success: function(layero, index){
                    layui.use('form', function(){
                        var form = layui.form;
                        form.render();

                        //监听提交
                        form.on('submit(editSubmit)', function(data){
                    /*        console.log(data.field)
                            alert(data.field);*/
                            editRecord(data.field, function() {
                                layer.close(index);
                                table.reload('transTable');
                            });
                            return false;
                        });
                    });
                }
            });
        }

        // 添加记录
        function addRecord(data, callback) {
            layui.$.ajax({
                url: '/transRec',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(res) {
                    layer.msg('添加成功');
                    callback && callback();
                },
                error: function() {
                    layer.msg('添加失败');
                }
            });
        }

        // 编辑记录
        function editRecord(data, callback) {
            layui.$.ajax({
                url: '/transRec',
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(res) {
                    layer.msg('编辑成功');
                    callback && callback();
                },
                error: function() {
                    layer.msg('编辑失败');
                }
            });
        }

        // 删除记录
        function deleteRecord(id, callback) {
            layui.$.ajax({
                url: '/transRec',
                type: 'DELETE',
                data: {id: id},
                success: function(res) {
                    layer.msg('删除成功');
                    callback && callback();
                },
                error: function() {
                    layer.msg('删除失败');
                }
            });
        }

        // 批量删除
        function batchDelete(ids) {
            layer.confirm('确定删除这'+ids.length+'条记录吗？', function(index){
                // 这里需要逐个删除，因为后端接口只支持单个删除
                var deletePromises = [];
                ids.forEach(function(id) {
                    var promise = new Promise(function(resolve, reject) {
                        layui.$.ajax({
                            url: '/transRec',
                            type: 'DELETE',
                            data: {id: id},
                            success: function(res) {
                                resolve(res);
                            },
                            error: function() {
                                reject();
                            }
                        });
                    });
                    deletePromises.push(promise);
                });

                Promise.all(deletePromises).then(function() {
                    layer.msg('删除成功');
                    table.reload('transTable');
                }).catch(function() {
                    layer.msg('部分删除失败');
                    table.reload('transTable');
                });

                layer.close(index);
            });
        }
    });
</script>
</body>
</html>
